<template>
  <div style="background: #eef1f2; padding: 20px">
    <div
      class="box"
      style="min-height: 450px; background: white; padding: 20px"
    >
      <div v-if="show">
        <el-form
          :inline="true"
          size="mini"
          :model="form"
          class="demo-form-inline"
        >
          <el-form-item label="自提点名称" style="margin-right: 100px">
            <el-input
              clearable
              v-model="form.addrName"
              placeholder="请输入自提点名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="search"
              icon="el-icon-search"
              size="small"
              >搜索</el-button
            >
            <el-button
              @click="resetForm(form)"
              size="small"
              i
              class="el-icon-delete"
              >清空</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <el-form>
        <el-row>
          <el-col :span="22">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="adds"
              >新增</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="batchDelete"
              :disabled="delId.length == 0"
              >批量删除</el-button
            >
          </el-col>
          <el-col :span="2" style="text-align: right">
            <el-button
              size="small"
              icon="el-icon-refresh"
              circle
              @click="shua"
            ></el-button>
            <el-button
              size="small"
              icon="el-icon-search"
              circle
              @click="kai"
            ></el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-row style="margin-top: 15px">
        <el-tag>
          <span style="margin-right: 10px"
            >当前表格已选择
            <span style="font-size: 16px; font-weight: 600">{{
              delId.length
            }}</span>
            项</span
          >
          <el-link
            :underline="false"
            type="primary"
            style="font-size: 12px"
            @click="toggleSelection()"
            >清 空</el-link
          >
        </el-tag>
      </el-row>
      <el-table
        ref="singleTable"
        :data="tableData"
        highlight-current-row
        :border="true"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          property="addrName"
          label="自提点名称"
          align="center"
        ></el-table-column>
        <el-table-column
          property="mobile"
          label="手机号"
          align="center"
        ></el-table-column>
        <el-table-column
          property="province"
          label="省份"
          align="center"
        ></el-table-column>
        <el-table-column
          property="city"
          label="城市"
          align="center"
        ></el-table-column>
        <el-table-column
          property="area"
          label="县/区"
          align="center"
        ></el-table-column>
        <el-table-column
          property="addr"
          label="地址"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="editRow(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteClue(scope.row.addrId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          background
          style="text-align: right"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <el-dialog
        ref="multipleTable"
        :title="title"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="名称" prop="addrName">
                <el-input
                  size="small"
                  show-word-limit
                  v-model="ruleForm.addrName"
                  placeholder="自提点名称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="省份" prop="provinceId">
                <el-select
                  v-model="ruleForm.provinceId"
                  placeholder="请选择省份"
                  @change="handleProvinceChange"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.areaId"
                    :label="item.areaName"
                    :value="item.areaId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="城市" prop="cityId">
                <el-select
                  v-model="ruleForm.cityId"
                  placeholder="请选择城市"
                  @change="handleCityChange"
                >
                  <el-option
                    v-for="item in optionss"
                    :key="item.areaId"
                    :label="item.areaName"
                    :value="item.areaId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="县/区" prop="areaId">
                <el-select
                  v-model="ruleForm.areaId"
                  placeholder="请选择县/区"
                  @change="handleAreaChange"
                >
                  <el-option
                    v-for="item in optionsss"
                    :key="item.areaId"
                    :label="item.areaName"
                    :value="item.areaId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="详细地址" prop="addr">
                <el-input
                  size="small"
                  show-word-limit
                  v-model="ruleForm.addr"
                  placeholder="详细地址"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              size="small"
              show-word-limit
              v-model="ruleForm.mobile"
              placeholder="手机号"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitDialog">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { pickList, pickArea, pickDelete, pickEdit, pickAdd } from "@/api/self";
export default {
  data() {
    return {
      delId: [],
      tableData: [],
      show: true,
      rules: {
        addrName: [
          { required: true, message: "请输入自提点名称", trigger: "blur" },
        ],
        province: [
          { required: true, message: "请选择省份", trigger: "change" },
        ],
        city: [{ required: true, message: "请选择城市", trigger: "change" }],
        area: [{ required: true, message: "请选择县/区", trigger: "change" }],
        addr: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      title: "",
      dialogVisible: false,
      options: [],
      addrId: [],
      options: [],
      optionss: [],
      optionsss: [],
      ruleForm: {
        addrName: "",
        provinceId: "", // 省份ID
        provinceName: "", // 省份名称
        cityId: "", // 城市ID
        cityName: "", // 城市名称
        areaId: "", // 区县ID
        areaName: "", // 区县名称
        addr: "",
        mobile: "",
      },
      pids: {
        pid: 0,
        t: new Date().getTime(),
        cityId: "",
        areaId: "",
      },
      total: 0,
      current: 1,
      size: 10,
      form: {
        addrName: "",
      },
    };
  },
  created() {
    this.pickList();
  },
  methods: {
    shua() {
      window.location.reload();
    },
    kai() {
      this.show = !this.show;
    },
    pickList() {
      let data = {
        current: this.current,
        size: this.size,
        t: new Date().getTime(),
      };
      pickList(data).then((res) => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },
    search() {
      this.current = 1;
      this.searchs();
    },
    searchs() {
      let data = {
        current: this.current,
        size: this.size,
        t: new Date().getTime(),
        addrName: this.form.addrName,
      };
      pickList(data).then((res) => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },
    resetForm() {
      this.form.addrName = "";
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.singleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.singleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.delId = [];
      console.log(this.delId);
      for (const item of val) {
        this.delId.push(item.addrId);
      }
    },
    handleSizeChange(val) {
      if (this.form.addrName) {
        this.searchs();
      } else {
        this.size = val;
        this.pickList();
      }
    },
    handleCurrentChange(val) {
      if (this.form.addrName) {
        this.searchs();
      } else {
        this.current = val;
        this.pickList();
      }
    },
    deleteClue(id) {
      this.$confirm(`此操作将永久删除编号为${id}的数据, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 点击确定
        pickDelete([id]).then((res) => {
          if (res.code === "00000") {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.pickList();
          } else {
            this.$message({
              type: "error",
              message: "删除失败，请重试。",
            });
          }
        });
      });
    },
    batchDelete() {
      this.$confirm(
        `此操作将永久删除编号为${this.delId}的数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 点击确定
          pickDelete(this.delId).then((res) => {
            if (res.code == "00000") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.pickList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    adds() {
      this.dialogVisible = true;
      this.title = "新增";
      this.ruleForm = {
        province: null,
        city: null,
        area: null,
      };
      this.pids = {
        pid: 0,
        t: new Date().getTime(),
      };
      pickArea(this.pids).then((res) => {
        if (res.code == "00000") {
          this.options = res.data;
          console.log(this.options);
        }
      });
    },
    handleProvinceChange(val) {
      const selectedProvince = this.options.find((item) => item.areaId === val);
      if (selectedProvince) {
        this.ruleForm.provinceName = selectedProvince.areaName;
      }
      // 获取城市数据
      this.pids.pid = val;
      pickArea(this.pids).then((res) => {
        this.optionss = res.data;
        // 清空下级选项
        this.ruleForm.cityId = "";
        this.ruleForm.cityName = "";
      });
    },

    // 处理城市选择
    handleCityChange(val) {
      const selectedCity = this.optionss.find((item) => item.areaId === val);
      if (selectedCity) {
        this.ruleForm.cityName = selectedCity.areaName;
      }
      // 获取区县数据
      this.pids.pid = val;
      pickArea(this.pids).then((res) => {
        this.optionsss = res.data;
      });
    },

    // 处理区县选择
    handleAreaChange(val) {
      console.log(val);
      console.log(this.optionsss);
      console.log(this.ruleForm.areaId);

      const selectedArea = this.optionsss.find((item) => item.areaId == val);
      if (selectedArea) {
        this.ruleForm.areaName = selectedArea.areaName;
        console.log(this.ruleForm.areaName);
      }
    },

    // 提交对话框
    submitDialog() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const formData = {
            addrName: this.ruleForm.addrName,
            provinceId: this.ruleForm.provinceId,
            province: this.ruleForm.provinceName, // 根据接口字段名调整
            cityId: this.ruleForm.cityId,
            city: this.ruleForm.cityName,
            areaId: this.ruleForm.areaId,
            area: this.ruleForm.areaName,
            addr: this.ruleForm.addr,
            mobile: this.ruleForm.mobile,
            t: new Date().getTime(),
          };

          // 根据操作类型调用接口
          const apiCall =
            this.title === "新增"
              ? pickAdd(formData)
              : pickEdit({ ...formData, addrId: this.ruleForm.addrId });

          apiCall.then((res) => {
            if (res.code === "00000") {
              this.$message.success(`${this.title}成功`);
              this.dialogVisible = false;
              this.pickList();
            }
          });
        }
      });
    },

    // 编辑行时填充数据
    editRow(row) {
      this.dialogVisible = true;
      this.title = "编辑";
      this.$nextTick(() => {
        this.$refs.ruleForm && this.$refs.ruleForm.clearValidate();
      });
      // 正确使用ID字段（假设row中有provinceId, cityId, areaId）
      this.ruleForm = {
        ...row,
        provinceId: row.provinceId, // 使用省份ID
        provinceName: row.province, // 省份名称
        cityId: row.cityId, // 城市ID
        cityName: row.city, // 城市名称
        areaId: row.areaId, // 区县ID（关键修改）
        areaName: row.area, // 区县名称
      };

      // 加载关联的区域数据
      this.loadAreaDataForEdit();
    },

    // 加载编辑所需的区域数据
    async loadAreaDataForEdit() {
      // 加载省份
      this.options = (await pickArea({ pid: 0 })).data;

      // 如果存在省份ID，加载城市
      if (this.ruleForm.provinceId) {
        this.optionss = (
          await pickArea({ pid: this.ruleForm.provinceId })
        ).data;
      }

      // 如果存在城市ID，加载区县
      if (this.ruleForm.cityId) {
        this.optionsss = (await pickArea({ pid: this.ruleForm.cityId })).data;
      }
    },
  },
};
</script>

 <style lang="scss" scoped>
::v-deep .el-dialog {
  margin-top: 15vh;
  width: 50% !important;
}
::v-deep .el-table thead {
  color: black !important;
}
::v-deep input[aria-hidden="true"] {
  display: none !important;
}
</style>